<template>
  <div>
    <Modal
      v-model="isShowModal"
      :title="title"
      @on-cancel="hide('formValidate')"
      :mask-closable="false"
      width="80vw"
    >
      <Form
        ref="formValidate"
        :model="params"
        :rules="ruleValidate"
        label-position="top"
      >
        <FormItem label="商品名称：" prop="goodsName">
          <Input v-model.trim="params.goodsName" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem label="商品图片：" prop="dyGoodsImages">
          <div class="hs-upload-image-box">
            <Upload
              ref="goodsGroup"
              :action="action"
              :headers="headers"
              :show-upload-list="false"
              name="file"
              multiple
              :on-success="uploadImagesSuccess"
              :default-file-list="defaultFileList"
            >
              <div class="hs-upload-add">
                <Icon type="md-add" size="30" />
              </div>
            </Upload>
            <div
              class="hs-upload-image"
              v-for="(item, index) in params.goodsImagesList"
              :key="item.response.data"
            >
              <template v-if="item.status === 'finished'">
                <img :src="item.response.data" />
                <!--删除图片-->
                <div class="hs-upload-image-delete" @click="delImage(index)">
                  <Icon type="md-close" />
                </div>
              </template>
              <template v-else>
                <Progress
                  v-if="item.showProgress"
                  :percent="item.percentage"
                  hide-info
                ></Progress>
              </template>
            </div>
          </div>
          <Alert show-icon closable style="margin-top:10px">
            建议上传600x600像素的图片，大小不超过500kb
          </Alert>
        </FormItem>
        <!-- <FormItem label="平台" prop="platform">
          <Select
            placeholder="请选择平台"
            v-model="params.platform"
            filterable
            @on-change="platformChange"
          >
            <Option
              v-for="(item, index) in platformList"
              :value="item.value"
              :key="index"
            >
              {{ item.label }}
            </Option>
          </Select>
        </FormItem> -->
        <FormItem label="小程序" prop="programId">
          <Select
            placeholder="请选择小程序"
            v-model="params.programId"
            filterable
            @on-change="programChange"
          >
            <Option
              v-for="(item, index) in programList"
              :value="item.programId"
              :key="item.programId"
            >
              {{ item.programName }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="服务" prop="serviceCode">
          <Select
            placeholder="请选择服务"
            v-model="params.serviceCode"
            filterable
            remote
          >
            <Option
              v-for="(item, index) in serviceCodeList"
              :value="item.value"
              :key="index"
            >
              {{ item.label }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="商品分类：" prop="goodsTypeIdA">
          <Cascader
            v-model="goodsTypeValue"
            :data="goodsTypeList"
            @on-change="goodsTypeChange"
          ></Cascader>
        </FormItem>
        <FormItem label="市场价：" prop="purchasePrice">
          <Input
            v-model.trim="params.purchasePrice"
            placeholder="请输入商品市场价"
            type="number"
          />
        </FormItem>
        <FormItem label="售价：" prop="price">
          <Input
            v-model.trim="params.price"
            placeholder="请输入商品售价"
            type="number"
          />
        </FormItem>
        <FormItem label="库存：" prop="stock">
          <Input
            v-model.trim="params.stock"
            placeholder="请输入库存"
            type="number"
          />
        </FormItem>
        <FormItem label="客服电话：" prop="customerPhoneNum">
          <Input
            v-model.trim="params.customerPhoneNum"
            placeholder="请输入客服电话"
            type="number"
          />
        </FormItem>
        <FormItem label="补充说明：" prop="notification">
          <Input
            v-model.trim="params.notification"
            placeholder="请输入补充说明"
            type="text"
          />
        </FormItem>
        <!-- <FormItem label="衣物数量：" prop="num">
          <Input
            v-model.trim="params.num"
            placeholder="请输入衣物数量"
            type="number"
          />
        </FormItem> -->
        <FormItem label="售卖起止时间：" prop="soldStartTime">
          <DatePicker
            @on-change="soldDateChange"
            v-model="params.soldDate"
            type="datetimerange"
            :editable="false"
            separator=" ~ "
            split-panels
            transfer
            placeholder="起止时间"
            style="width: 800px"
          ></DatePicker>
        </FormItem>

        <!-- <FormItem label="商品详情：" prop="goodsInfo">
          <hs-edit
            ref="edit"
            id="0"
            v-if="isEditShow"
            :value="params.goodsInfo"
            @edit-out="editOut"
          ></hs-edit>
        </FormItem> -->
      </Form>

      <!-- 重写对话框底部按钮 -->
      <div slot="footer">
        <Button @click="hide('formValidate')">取消</Button>
        <Button
          v-if="type != 1"
          type="primary"
          @click="handleSubmit('formValidate')"
          :loading="loadingBtn"
        >
          <span v-if="!loadingBtn">确定</span>
          <span v-else>请稍候...</span>
        </Button>
      </div>
    </Modal>

    <!-- 商品规格设置 -->
    <goods-sku-ope
      ref="goodsSkuOpe"
      :specGroup="params.specGroup"
      :goodsSkuList="params.goodsSkuList"
      @skuEditDone="skuEditDone"
    ></goods-sku-ope>
  </div>
</template>

<script>
  import hsEdit from '@/components/hs-edit';
  import goodsSkuOpe from './goods-sku-ope';
  import { get } from 'lodash';
  import {
    platformList,
    companyList,
    serviceCodeList
  } from '@/constant/program';

  export default {
    name: 'goods-ope',
    props: ['freightList'],
    data() {
      return {
        serviceCodeList,
        platformList,
        allProgram: [],
        isShowModal: false,
        isEditShow: false,
        isShowIsSkuBtn: false,
        isShowFreightPrice: true,
        isShowFreightId: false,
        loadingBtn: false,
        title: '查看信息',
        goodsTypeValue: [],
        goodsTypeList: [],
        defaultFileList: [],
        type: 0,
        action: this.$uploadURL,
        headers: {
          token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
        },
        params: {
          num: '',
          notification: '',
          customerPhoneNum: '',
          stock: 0,
          goodsMallId: '',
          goodsName: '',
          thumbnail: '',
          goodsTypeIdA: '',
          goodsTypeIdB: '',
          freightPrice: '',
          freightId: '',
          goodsInfo: '',
          dyGoodsImages: '',
          goodsImagesList: [],
          purchasePrice: 0,
          price: '',
          isSku: '0',
          isUpShelf: '2',
          goodsSkuList: [],
          notification: '',
          soldDate: [],
          soldStartTime: '',
          soldEndTime: '',
          platform: '3',
          programId: '',
          serviceCode: ''
        },
        ruleValidate: {
          goodsName: [
            { required: true, message: '商品名称不能为空', trigger: 'blur' }
          ],
          goodsTypeIdA: [
            {
              required: true,
              message: '请选择商品分类'
            }
          ],
          dyGoodsImages: [{ required: true, message: '商品图片不能为空' }],
          customerPhoneNum: [{ required: true, message: '客服电话不能为空' }],
          num: [{ required: true, message: '数量不能为空' }],
          stock: [{ required: true, message: '库存不能为空' }],
          soldStartTime: [{ required: true, message: '售卖时间不能为空' }],
          purchasePrice: [{ required: true, message: '市场价不能为空' }],
          price: [{ required: true, message: '售价不能为空' }],
          serviceCode: [
            { required: true, message: '服务不能为空', trigger: 'blur' }
          ],
          programId: [{ required: true, message: '小程序不能为空' }]
        }
      };
    },
    computed: {
      programList() {
        return this.allProgram
          .filter(item => item.platform == this.params.platform)
          .map(item => ({ ...item, programId: item.programId.toString() }));
      }
    },
    mounted() {
      // 商品-查询分类
      this.queryMallGoodsTypeList();
      this.queryAllProgram();
    },
    methods: {
      platformChange() {
        this.goodsTypeChange(['', '']);
        this.params.programId = '';
        this.queryAllProgram();

        this.queryMallGoodsTypeList();
      },
      programChange() {
        this.goodsTypeChange(['', '']);
        this.queryMallGoodsTypeList();
      },
      queryAllProgram() {
        this.axios
          .post('/program/findList', { rows: 999, page: 1 })
          .then(res => {
            if (res.status == 200) {
              this.allProgram = res.data.rows;
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查询小程序列表接口报错',
                duration: 0
              });
            }
          });
      },
      soldDateChange(val) {
        console.log(val);
        this.params.soldStartTime = get(val, [0]);
        this.params.soldEndTime = get(val, [1]);
      },
      // 点击提交验证
      handleSubmit(name) {
        console.log(this.params);
        // 判断商品二级和三级分类
        if (!this.params.goodsTypeIdB) {
          this.$Message.error('请选择商品二级分类');
          return false;
        }

        this.$refs[name].validate(valid => {
          if (valid) {
            // this.$Message.error('验证通过');
            /**
             * type判断
             * 1.查看 2.新增 3.编辑
             */
            switch (this.type) {
              case 1:
                // this.title = '查看商品';
                break;
              case 2:
                // 新增商品
                this.addGoods();
                break;
              case 3:
                // 编辑商品
                this.updateGoods();
                break;
              default:
                this.$Notice.error({
                  title: '商品管理',
                  desc: '查看，新增，编辑区分判断报错',
                  duration: 0
                });
                break;
            }
          } else {
            this.$Message.error('还有信息没有填写合格哦~');
          }
        });
      },
      // 显示模态框
      show(type, row) {
        this.isShowModal = true;
        this.isEditShow = true;
        this.type = type;
        /**
         * type判断
         * 1.查看 2.新增 3.编辑
         */
        switch (type) {
          case 1:
            this.title = '查看商品';
            this.findInfo(row);
            break;
          case 2:
            this.title = '新增商品';
            break;
          case 3:
            this.title = '编辑商品';
            this.findInfo(row);
            break;
          default:
            this.$Notice.error({
              title: '商品管理',
              desc: '查看，新增，编辑模态框报错',
              duration: 0
            });
            break;
        }
      },
      // 新增商品
      addGoods() {
        this.$Spin.show();
        this.axios.post('/dyGoodsMall/addGoods', this.params).then(res => {
          setTimeout(() => {
            this.$Spin.hide();
          }, 300);
          if (res.status == 200) {
            this.$emit('changeDate');
            this.$Message.success('操作成功.');
            this.hide('formValidate');
          }
          if (res.status == 201) {
            this.$Message.error(res.msg);
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '新增商品接口报错',
              duration: 0
            });
          }
        });
      },
      // 编辑商品
      updateGoods() {
        this.$Spin.show();
        this.axios.post('/dyGoodsMall/updateGoods', this.params).then(res => {
          setTimeout(() => {
            this.$Spin.hide();
          }, 300);
          if (res.status == 200) {
            this.$emit('changeDate');
            this.$Message.success('操作成功.');
            this.hide('formValidate');
          }
          if (res.status == 201) {
            this.$Message.error(res.msg);
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '编辑商品接口报错',
              duration: 0
            });
          }
        });
      },
      // 商城分类-查询商城分类
      queryMallGoodsTypeList() {
        this.axios
          .post('/mallGoodsType/queryMallGoodsTypeList', {
            platform: this.params.platform,
            programId: this.params.programId,
            page: 1,
            rows: 1000
          })
          .then(res => {
            if (res.status == 200) {
              this.goodsTypeList = res.data.map(item => ({
                value: item.goodsMallTypeId,
                label: item.goodsTypeName,
                children: item.children.map(item1 => ({
                  value: item1.goodsMallTypeId,
                  label: item1.goodsTypeName
                }))
              }));
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查询商城分类接口报错',
                duration: 0
              });
            }
          });
      },
      // 查询商品详情
      findInfo(row) {
        this.$Spin.show();
        this.axios
          .post('/dyGoodsMall/findInfo', {
            goodsMallId: row.goodsMallId
          })
          .then(res => {
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              const goodsMall = res.data.goodsMall;
              Object.assign(this.params, {
                ...goodsMall,
                programId: String(goodsMall.programId),
                goodsImagesList: [],
                mallGoodsId: goodsMall.goodsMallId,
                soldDate: [goodsMall.soldStartTime, goodsMall.soldEndTime]
              });
              this.goodsTypeValue = [
                res.data.goodsMall.goodsTypeIdA,
                res.data.goodsMall.goodsTypeIdB
              ];
              if (res.data.goodsMall.dyGoodsImages) {
                let dyGoodsImages = res.data.goodsMall.dyGoodsImages.split(',');
                // 回显图片组
                for (let i in dyGoodsImages) {
                  this.defaultFileList.push({
                    response: {
                      data: dyGoodsImages[i]
                    }
                  });
                  // 回显图片组
                  this.params.goodsImagesList.push({
                    percentage: 100,
                    status: 'finished',
                    showProgress: false,
                    response: {
                      data: dyGoodsImages[i]
                    }
                  });
                }
              }
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查看商品详情接口报错',
                duration: 0
              });
            }
          });
      },
      // 显示规格
      showSku() {
        this.$refs.goodsSkuOpe.show();
      },
      // 编辑规格之后返回的数据
      skuEditDone(e) {
        // console.log(e)
        this.params.specGroup = JSON.stringify(e.specGroup);
        this.params.goodsSkuList = e.goodsSkuList;
      },
      // 富文本编辑器返回的内容
      editOut(e) {
        this.params.goodsInfo = e;
      },
      // 商品分类改变
      goodsTypeChange(e) {
        this.goodsTypeValue = e;
        this.params.goodsTypeIdA = e[0];
        this.params.goodsTypeIdB = e[1];
        console.log(this.params.goodsTypeIdA, this.params.goodsTypeIdB);
      },
      // 运费模板改变
      freightIdChange(e) {
        // console.log(e)
        this.params.freightId = e;
      },
      // 商品首图上传成功
      uploadFirstSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.params.thumbnail = response.data;
          this.formatImagePath();
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传图片首图接口报错',
            duration: 0
          });
        }
      },
      // 商品组图
      uploadImagesSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.params.goodsImagesList = [...this.$refs.goodsGroup.fileList];
          this.formatImagePath();
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传商品组图接口报错',
            duration: 0
          });
        }
      },
      // 删除图片
      delImage(index) {
        const fileList = this.$refs.goodsGroup.fileList;
        fileList.splice(index, 1);
        this.params.goodsImagesList = fileList;
        this.formatImagePath();
      },
      // 格式化图片参数格式
      formatImagePath() {
        let arr = [];
        for (let i in this.params.goodsImagesList) {
          if (this.params.goodsImagesList[i].response) {
            arr.push(this.params.goodsImagesList[i].response.data);
          }
        }
        // 判断有没有缩略图，如果有放在第一个位置并标识为首图
        if (this.params.thumbnail) {
          arr.unshift(this.params.thumbnail);
        }
        // 将图片的值赋值给参数
        this.params.dyGoodsImages = arr.join(',');
      },
      // 关闭模态框
      hide(name) {
        this.isShowModal = false;
        this.isEditShow = false;
        this.params.freightId = '';
        this.goodsTypeValue = [];
        this.params.goodsImagesList = [];
        this.params.specGroup = {};
        this.params.goodsSkuList = [];
        this.params.freightPrice = '';
        // 清空图片组上传的fileList
        this.$refs.goodsGroup.clearFiles();
        this.defaultFileList = [];
        this.$refs[name].resetFields();
      }
    },
    components: {
      hsEdit,
      goodsSkuOpe
    }
  };
</script>

<style scoped lang="less">
  .hs-upload-image-box {
    display: flex;
    align-items: center;
    position: relative;

    .hs-upload-image {
      width: 145px;
      height: 145px;
      margin-top: -8px;
      margin-left: 10px;
      border: 1px solid #efefef;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .hs-upload-image-delete {
        position: absolute;
        top: -8px;
        right: -8px;
        width: 20px;
        height: 20px;
        background-color: red;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ffffff;
        border-radius: 50%;
      }

      .hs-upload-image-setting {
        position: absolute;
        bottom: 0;
        width: 100%;
        color: #ffffff;
        height: 40px;
        display: none;
        align-items: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.8);
      }

      img {
        width: 100%;
        height: 100%;
      }
    }

    .hs-upload-add {
      cursor: pointer;
      width: 145px;
      height: 145px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #cccccc;
      transition: all 0.3s;

      &:hover {
        color: #2d8cf0;
        border: 1px dashed #2d8cf0;
      }
    }
  }
</style>
